<template>
	<view class="content">
		<view style="background-color: #fff;">
			<zb-tab style="margin: 20rpx 0rpx;" :activeStyle="{fontWeight: 'bold',transform: 'scale(1.1)'}"
				:data="tabList" v-model="active" @change="onTabChange"></zb-tab>
		</view>
		<view v-for="(order, index) in orderList" :key="index" class="order-item">
			<view class="order-header">
				<text class="order-id">订单编号：{{order.orderNumber}}</text>
				<text class="order-status">{{getStatusText(order.state)}}</text>
			</view>
			<view class="product-info" @click="goGoodsDetail(order)">
				<image :src="order.orderCommodityDtoList[0].commodityDto.pictureIntegrationDtoS[0] &&
					order.orderCommodityDtoList[0].commodityDto.pictureIntegrationDtoS[0].pictureUrl" class="product-image"></image>
				<view class="product-details">
					<view class="product-name">{{order.orderCommodityDtoList[0].commodityDto.commodityName}}</view>
					<view class="product-commodity">
						{{order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.attributeName}}:
						{{order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.attributeValue}}
						<span
							v-if="order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto &&
									order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationName && 
									order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationValue">
							,{{ order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationName }}:
							{{ order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.specificationValue }}
						</span>
					</view>
					<view class="product-price-specs">
						<text
							class="product-price">￥{{order.orderCommodityDtoList[0].commodityDto.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.sellingPrice}}</text>
						<text class="product-specs">×{{order.orderCommodityDtoList[0].bayCount}}</text>
					</view>
					<view class="quantity-total" style="text-align: right;">
						<text>共计{{order.orderCommodityDtoList[0].bayCount}}件商品,</text>
						<text>合计：￥<text style="color: red;">{{order.amountActuallyPaid}}</text></text>
					</view>
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="order-actions">
				<view class="button" @click="onViewDetails(order)">查看详情</view>
				<view class="button" @click="onDeleteOrder(order)">删除订单</view>
				<template v-if="order.state == 0">
					<view class="button" @click="onPayOrder(order)">支付</view>
					<view class="button" @click="onCancelOrder(order)">取消订单</view>
				</template>
				<template v-if="order.state == 4">
					<view class="button" @click="onReceiptOfGoods(order)">确认收货</view>
				</template>
				<template v-if="order.state == 6">
					<view class="button" @click="onEvaluate(order)">去评价</view>
				</template>
			</view>
		</view>
		<view v-if="!orderList.length">
			<image style="margin:10%;" src='../../../static/null/null.png'></image>
		</view>
	</view>
</template>

<script>
	import {
		getOrderList,
		delOrder,
		editOrder,
		cancellOrder,
		addPayment
	} from '@/api/order.js';
	import wx from 'jweixin-module';
	export default {
		data() {
			return {
				orderList: [],
				isFirstLoad: true,
				active: 100,
				tabList: [{
						name: '全部',
						value: 100
					},
					{
						name: '待付款',
						value: 0
					},
					{
						name: '待发货',
						value: 2
					},
					{
						name: '待收货',
						value: 4
					},
					{
						name: '待评价',
						value: 6
					},
				],
				pageSize: 10,
				pageNumber: 1,
				hasMore: true,
			};
		},
		onShow() {
			this.onTabChange()
		},
		methods: {
			getStatusText(state) {
				console.log(state, "state")
				const stateMap = {
					0: '待付款',
					1: '付款超时',
					2: '待发货',
					3: '已取消',
					4: '已发货',
					5: '已收货',
					6: '待评价',
					7: '已评价',
					8: '已完成',
					9: '发起退款申请',
					10: '退款申请通过',
					11: '退款申请驳回'
				};
				return stateMap[state] || '未知状态';
			},
			goGoodsDetail(order) {
				console.log('查看商品:', order);
				uni.navigateTo({
					url: '/pages/classification/goodsDetail/index?id=' + order.orderCommodityDtoList[0].commodityId
				})
			},
			onViewDetails(order) {
				console.log('查看详情:', order);
				uni.navigateTo({
					url: '/pages/my/orderDetail/index?id=' + order.id
				})
			},
			onPayOrder(order) {
				console.log('支付订单:', order);
				addPayment(order.orderNumber, 1).then(res => {
					console.log(res, "微信支付");
					// 检查 WeixinJSBridge 是否可用
					if (typeof WeixinJSBridge === "undefined") {
						console.error(
							"WeixinJSBridge is not available. Please open this page in WeChat browser.");
						uni.showToast({
							title: '请在微信浏览器中打开此页面',
							icon: 'none',
							duration: 2000
						});
						return;
					}

					// 调用 WeixinJSBridge 进行支付
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: res.data.appId,
							timeStamp: "" + res.data.timeStamp, // 强制转换为字符串
							nonceStr: res.data.nonceStr,
							package: res.data.packageValue,
							signType: res.data.signType,
							paySign: res.data.paySign
						},
						function(response) {
							console.log(response, "支付回调结果");
							handlePaymentResponse(response);
						}
					);
				}).catch(error => {
					console.error("创建订单失败：", error);
					uni.showToast({
						title: '创建订单失败，请稍后再试',
						icon: 'none',
						duration: 2000
					});
				});

				// 定义处理支付响应的函数
				function handlePaymentResponse(response) {
					if (response.err_msg === "get_brand_wcpay_request:ok") {
						// 支付成功后的处理逻辑
						console.log("支付成功！");
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 2000
						});
						// 可以在这里添加更多支付成功的逻辑，例如跳转到订单详情页等
						this.getList()
					} else {
						// 支付失败或其他情况的处理逻辑
						console.error("支付失败或用户取消支付：", response.err_msg);
						uni.showToast({
							title: '支付失败或已取消',
							icon: 'none',
							duration: 2000
						});

						// 根据需要可以提供给用户重新尝试支付的机会
					}
				}
				console.log('Submit Order with Data:', data);
			},
			onCancelOrder(order) {
				cancellOrder(order.orderNumber).then(res => {
					uni.showToast({
						icon: "none",
						title: '取消成功'
					});
					this.pageNumber = 1
					this.orderList = []
					this.getList()
				})
			},
			onDeleteOrder(order) {
				console.log('删除订单:', order);
				const data = {
					id: order.id,
					userDeletion: 1
				}
				delOrder(data).then(res => {
					uni.showToast({
						icon: "none",
						title: '删除成功'
					});
					this.pageNumber = 1
					this.orderList = []
					this.getList()
				})
			},
			onReceiptOfGoods(order) {
				console.log('收货:', order);
				const params = {
					...order,
					state: 5
				};
				editOrder(params).then(res => {
					uni.showToast({
						icon: "none",
						title: '收货成功'
					});
					this.pageNumber = 1
					this.orderList = []
					this.getList()
				})
			},
			onEvaluate(order) {
				console.log('去评价:', order);
				uni.navigateTo({
					url: '/pages/my/myOrder/addEvaluate/index?commodityId=' + order.orderCommodityDtoList[0]
						.commodityId + '&orderId=' + order.id
				})
			},
			getList() {
				const params = {
					pageSize: this.pageSize,
					pageNumber: this.pageNumber,
					state: this.active,
					userDeletion: 0,
				};
				console.log(params.state, "params.state")
				if (params.state == 100) {
					params.state = null
				}
				console.log(params.state, "params.state")
				getOrderList(params).then(res => {
					this.orderList = [...this.orderList, ...res.data.records];
					if (res.data.length < this.pageSize) {
						this.hasMore = false; // 如果返回的数据少于请求的数量，说明没有更多的数据了
					} else {
						this.pageNumber += 1;
					}
				})
			},
			onTabChange(newIndex) {
				if (this.isFirstLoad) {
					this.isFirstLoad = false;
					// 不执行其他逻辑，因为这是首次加载
					return;
				}
				// 执行正常的逻辑
				console.log('Tab changed to index:', newIndex);
				this.active = newIndex.value;
				console.log(this.active, "onTabChange")
				this.pageNumber = 1; // 切换标签时重置页码
				this.orderList = []; // 清空列表
				this.hasMore = true; // 重置是否有更多数据的状态
				this.getList(); // 加载新的数据
			}
		},
		onReachBottom() {
			this.getList();
		},
	};
</script>
<style lang="scss">
	@import '@/uni.scss';

	.content {
		min-height: 100vh;
		background-color: #F3F3F3;
	}

	.order-item {
		padding: 20rpx;
		margin: 20rpx;
		background-color: $uni-bg-color-white;

		.order-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 10rpx;

			.order-id,
			.order-status {
				font-size: 28rpx;
			}
		}

		.product-info {
			display: flex;
			margin-bottom: 10rpx;
			padding-bottom: 10rpx;
			border-bottom: 2rpx solid $uni-border-color;

			.product-image {
				width: 180rpx;
				height: 180rpx;
				margin-right: 20rpx;
			}

			.product-details {
				flex-grow: 1;

				.product-name {
					font-size: 32rpx;
					line-height: 1.5;
					max-height: 96rpx; // 两行的高度
					overflow: hidden;
				}

				.product-commodity {
					font-size: 24rpx;
					color: #777;
				}

				.product-price-specs {
					display: flex;
					justify-content: space-between;
					margin-top: 10rpx;

					.product-price {
						font-weight: bold;
					}

					.product-specs {
						color: #777;
					}
				}

				.quantity-total {
					font-size: 28rpx;
					margin-top: 10rpx;
					color: #777;
				}
			}
		}

		.order-actions {
			display: flex;
			justify-content: flex-end;
			text-align: center;

			.button {
				width: 140rpx;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 28rpx;
				margin-right: 10rpx;
				border-radius: 50rpx;
				border: 2rpx solid $uni-border-color;
			}
		}
	}
</style>